package gl.android.biyiqing;

import gl.API;
import gl.App;
import gl.SplashActivity;
import gl.android.biyiqing.bean.Result;
import gl.android.biyiqing.event.OnRegiestSuccess;
import gl.common.BaseControl;
import gl.common.UserInfo;
import gl.common.UserManger;
import gl.uitls.AndroidUtil;
import gl.uitls.DimenUtil;
import gl.uitls.GLApkVersionManger;
import gl.uitls.MD5;
import gl.uitls.Tip;

import java.util.Calendar;

import net.tsz.afinal.http.AjaxCallBack;

import org.json.JSONException;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.annotation.TargetApi;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.graphics.Rect;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

/**
 * Activity which displays a login screen to the user, offering registration as
 * well.
 */
public class LoginActivity extends BYQBaseActivity {

	/**
	 * The default email to populate the email field with.
	 */
	public static final String EXTRA_EMAIL = "com.example.android.authenticatordemo.extra.EMAIL";

	public String IMEI = AndroidUtil.getIMEI();

	/**
	 * Keep track of the login task to ensure we can cancel it if requested.
	 */
	private UserLoginTask mAuthTask = null;

	// Values for email and password at the time of the login attempt.
	private String mEmail = "";
	private String mPassword = "";
	// UI references.
	private EditText mEmailView;
	private EditText mPasswordView;
	private View mLoginFormView;
	private View mLoginStatusView;
	private TextView mLoginStatusMessageView;
	// private CheckBox checkBox1;
	private ViewGroup content;
	private ImageView img;
	boolean isAutoLogin = false;
	
	public void onEvent(OnRegiestSuccess mDataLoading) {
		mEmailView.setText(AndroidUtil.getValueFromSharePreferences(key_USERNAME, "0"));
		mPasswordView.setText(AndroidUtil.getValueFromSharePreferences(key_PASSWORD, "0"));
		needMD5PW = false;
		mPassword = AndroidUtil.getValueFromSharePreferences(key_PASSWORD, "0"); 
		checkIsAutoLogin();
		if (isAutoLogin) {
			attemptLogin();
		}
	}
	@Override
	protected void onResume() {
		super.onResume();
		checkIsAutoLogin();
		if (isAutoLogin) {
			attemptLogin();
		}
			
	}

	@Override
	public void onBackPressed() {
		super.onBackPressed();
		App.getApp().exit();
	}

	private boolean needMD5PW;
	public static final String key_USERNAME = "USERNAME";
	public static final String key_PASSWORD = "PASSWORD";

	private ViewGroup ss;

	private Rect frame;

	// Content View Elements

	private LinearLayout activity_login_scroll;
	private View login_form;
	private EditText login_nick;
	private ImageView login_nick_del;
	private EditText login_password;
	private ImageView login_pass_del;
	private TextView login_register_btn;
	private TextView login_login_btn;

	// End Of Content View Elements

	private void bindViews() {

		activity_login_scroll = (LinearLayout) findViewById(R.id.activity_login_scroll);
		content = (LinearLayout) findViewById(R.id.content);
		img = (ImageView) findViewById(R.id.img);
		login_form = (View) findViewById(R.id.login_form);
		login_nick = (EditText) findViewById(R.id.login_nick);
		login_nick_del = (ImageView) findViewById(R.id.login_nick_del);
		login_password = (EditText) findViewById(R.id.login_password);
		login_pass_del = (ImageView) findViewById(R.id.login_pass_del);
		login_register_btn = (TextView) findViewById(R.id.login_register_btn);
		login_login_btn = (TextView) findViewById(R.id.login_login_btn);
	}

	class DelOnclickListener implements View.OnClickListener {

		private EditText editview;

		public DelOnclickListener(EditText login_nick) {
			this.editview = login_nick;
		}

		@Override
		public void onClick(View arg0) {
			editview.setText("");
		}

	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		// if (BuildConfig.DEBUG) {
		// mEmail = "13902210392";
		// mPassword = "e99a18c428cb38d5f260853678922e03";
		// }
		new GLApkVersionManger().autoManger(this, "byq");
		setContentView(R.layout.activity_login_byq);
		bindViews();
		login_nick_del.setOnClickListener(new DelOnclickListener(login_nick));
		login_pass_del
				.setOnClickListener(new DelOnclickListener(login_password));
		String username = getIntent().getStringExtra(EXTRA_EMAIL);
		if (!TextUtils.isEmpty(username)) {
			// Set up the login form.
			mEmail = username;
		}

		username = AndroidUtil.getValueFromSharePreferences(key_USERNAME, "0");
		if (!TextUtils.isEmpty(username)) {
			// Set up the login form.
			mEmail = username;
		}
		String password;

		password = AndroidUtil.getValueFromSharePreferences(key_PASSWORD, "0");

		if (checkIsAutoLogin()) {
			
		}
		else {
			startActivity(new Intent(this, SplashActivity.class));
		}
		if (!TextUtils.isEmpty(password)) {
			mPassword = password;
			// checkBox1.setChecked(true);
		}
		mEmailView = login_nick;
		mEmailView.setText(mEmail);
		if (!TextUtils.isEmpty(mEmail)) {
			mEmailView.setSelection(mEmail.length());
		}
		mPasswordView = login_password;
		mPasswordView
				.setOnEditorActionListener(new TextView.OnEditorActionListener() {
					@Override
					public boolean onEditorAction(TextView textView, int id,
							KeyEvent keyEvent) {
						if (id == R.id.login || id == EditorInfo.IME_NULL) {
							attemptLogin();
							return true;
						}
						return false;
					}
				});
		OnTouchListener mOnTouchListener = new OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				if (event.getAction() == MotionEvent.ACTION_DOWN && ss != null) {
					ss.setLayoutParams(new FrameLayout.LayoutParams(
							LayoutParams.MATCH_PARENT,
							LayoutParams.MATCH_PARENT));
					new Handler().postDelayed(new Runnable() {

						@Override
						public void run() {
							ss.scrollTo(0, (int) DimenUtil.dp2px(160));

						}
					}, 600);

				}
				return false;
			}
		};
		mEmailView.setOnTouchListener(mOnTouchListener);
		mPasswordView.setOnTouchListener(mOnTouchListener);
		mPasswordView.setText(mPassword);

		mPasswordView.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				if (s != null) {
					mPassword = s.toString();
				}

			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
			}

			@Override
			public void afterTextChanged(Editable s) {
				needMD5PW = true;
			}
		});

		mLoginFormView = findViewById(R.id.login_form);
		mLoginStatusView = findViewById(R.id.login_status);
		mLoginStatusMessageView = (TextView) findViewById(R.id.login_status_message);

		findViewById(R.id.login_login_btn).setOnClickListener(
				new View.OnClickListener() {
					@Override
					public void onClick(View view) {
						attemptLogin();
					}
				});
		findViewById(R.id.login_register_btn).setOnClickListener(
				new View.OnClickListener() {
					@Override
					public void onClick(View view) {
						startActivity(new Intent(LoginActivity.this,
								RegistActivity.class));
					}
				});
		findViewById(R.id.login_findpw).setOnClickListener(
				new View.OnClickListener() {
					@Override
					public void onClick(View view) {
						startActivity(new Intent(LoginActivity.this,
								PassWordResetActivity.class));
					}
				});
	}

	public boolean checkIsAutoLogin() {
		return isAutoLogin = "true".equals(AndroidUtil.getValueFromSharePreferences("isAutoLogin", "0")
				)?true:false;
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		getMenuInflater().inflate(R.menu.login, menu);
		return true;
	}

	/**
	 * Attempts to sign in or register the account specified by the login form.
	 * If there are form errors (invalid email, missing fields, etc.), the
	 * errors are presented and no actual login attempt is made.
	 */
	public void attemptLogin() {
		if (mAuthTask != null) {
			return;
		}
		Calendar mCalendar = Calendar.getInstance();
		mCalendar.set(2025, Calendar.MARCH, 5);
		if (Calendar.getInstance().after(mCalendar)) {
			Tip.show("版本已于2025年2月5过期，请联系开发者,开通自动升级功能");
			return;
		}

		Log.i("Calendar",
				Calendar.getInstance().get(Calendar.YEAR) + "/"
						+ Calendar.getInstance().get(Calendar.MONTH) + "/"
						+ Calendar.FEBRUARY + "/"
						+ Calendar.getInstance().get(Calendar.DAY_OF_MONTH));
		// Reset errors.
		mEmailView.setError(null);
		mPasswordView.setError(null);

		// Store values at the time of the login attempt.
		mEmail = mEmailView.getText().toString();
		// mPassword = mPasswordView.getText().toString();

		boolean cancel = false;
		View focusView = null;

		// Check for a valid password.
		if (TextUtils.isEmpty(mPassword)) {
			mPasswordView.setError(getString(R.string.error_field_required));
			focusView = mPasswordView;
			cancel = true;
		}
		else if (mPassword.length() < 4) {
			mPasswordView.setError(getString(R.string.error_invalid_password));
			focusView = mPasswordView;
			cancel = true;
		}

		// Check for a valid email address.
		if (TextUtils.isEmpty(mEmail)) {
			mEmailView.setError(getString(R.string.error_field_required));
			focusView = mEmailView;
			cancel = true;
		}

		if (cancel) {
			// There was an error; don't attempt login and focus the first
			// form field with an error.
			focusView.requestFocus();
		}
		else {
			// Show a progress spinner, and kick off a background task to
			// perform the user login attempt.
			mLoginStatusMessageView.setText(R.string.login_progress_signing_in);
			showProgress(true);
			mAuthTask = new UserLoginTask();
			mAuthTask.execute();
		}
	}

	/**
	 * Shows the progress UI and hides the login form.
	 */
	@TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
	private void showProgress(final boolean show) {
		// On Honeycomb MR2 we have the ViewPropertyAnimator APIs, which allow
		// for very easy animations. If available, use these APIs to fade-in
		// the progress spinner.
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
			int shortAnimTime = getResources().getInteger(
					android.R.integer.config_shortAnimTime);

			mLoginStatusView.setVisibility(View.VISIBLE);
			mLoginStatusView.animate().setDuration(shortAnimTime)
					.alpha(show ? 1 : 0)
					.setListener(new AnimatorListenerAdapter() {
						@Override
						public void onAnimationEnd(Animator animation) {
							mLoginStatusView.setVisibility(show ? View.VISIBLE
									: View.GONE);
						}
					});

			mLoginFormView.setVisibility(View.VISIBLE);
			mLoginFormView.animate().setDuration(shortAnimTime)
					.alpha(show ? 0 : 1)
					.setListener(new AnimatorListenerAdapter() {
						@Override
						public void onAnimationEnd(Animator animation) {
							mLoginFormView.setVisibility(show ? View.GONE
									: View.VISIBLE);
						}
					});
		}
		else {
			// The ViewPropertyAnimator APIs are not available, so simply show
			// and hide the relevant UI components.
			mLoginStatusView.setVisibility(show ? View.VISIBLE : View.GONE);
			mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
		}
	}

	/**
	 * Represents an asynchronous login/registration task used to authenticate
	 * the user.
	 */
	public class UserLoginTask {

		public void execute() {
			String temp = mPassword;
			if (needMD5PW) {
				temp = MD5.md5(temp);
			}

			final String pw = temp;
			BaseControl.get(API.URL + "Login?name=%s&pwd=%s&IMEI=%S",
					new AjaxCallBack<String>() {
						@Override
						public void onSuccess(String t) {
							super.onSuccess(t);
							mAuthTask = null;
							showProgress(false);
							Result userList2 = null;
							try {
								userList2 = Result.parse(t);
							} catch (NullPointerException e) {
								e.printStackTrace();
								onFailure(e, 0, "服务器没有返回数据");
							} catch (JSONException e) {
								e.printStackTrace();
								onFailure(e, 0, "服务器返回错误的格式");
							}
							if (userList2.isValue()) {
								if (!TextUtils.isEmpty(userList2.getMsg())
										&& "2".equals(userList2.getMsg())) {

									UserManger.getInstance().username = mEmail;
									UserManger.getInstance().password = pw;
									UserManger.getInstance().token = IMEI;
									UserManger.getInstance().userinfo = new Gson()
											.fromJson(
													userList2.data.toString(),
													new TypeToken<UserInfo>() {
													}.getType());
									UserManger.getInstance().userid = UserManger
											.getInstance().userinfo.getUserid();
									saveUserPassword2SP();
									saveIsAutoLogin();
									Intent mIntent = new Intent(
											LoginActivity.this,
											BottomTabActivity.class);
									startActivity(mIntent);
									// startService(new
									// Intent(LoginActivity.this,
									// PushService.class));
									finish();
								}
								else if (!TextUtils.isEmpty(userList2.getMsg())
										&& "1".equals(userList2.getMsg())) {
									Tip.show("密码错误");

								}
								else if (!TextUtils.isEmpty(userList2.getMsg())
										&& "0".equals(userList2.getMsg())) {
									Tip.show("用户名不存在");

								}

							}
							else {
								Tip.showTipDialog(LoginActivity.this,
										"返回的用户资料数据异常" + userList2.getMsg(),
										"登陆失败", new OnClickListener() {
											@Override
											public void onClick(
													DialogInterface dialog,
													int which) {
											}

										});
							}
						}

						@Override
						public void onFailure(Throwable t, int errorNo,
								String strMsg) {
							super.onFailure(t, errorNo, strMsg);
							mAuthTask = null;
							showProgress(false);
							mPasswordView.setError("无法连接,请检查网络或者联系管理员");
							mPasswordView.requestFocus();
						}
					}, mEmail, pw, IMEI);

		}

		protected void saveIsAutoLogin() {
			AndroidUtil.saveToSharePreferences("isAutoLogin", "0", "true");

		}
	}

	private void saveUserPassword2SP() {
		if (isSaveLoginInfo()) {
			AndroidUtil.saveToSharePreferences(key_USERNAME, "0",
					UserManger.getInstance().username);
			AndroidUtil.saveToSharePreferences(key_PASSWORD, "0",
					UserManger.getInstance().password);
		}
		else {
			AndroidUtil.saveToSharePreferences(key_USERNAME, "0", "");
			AndroidUtil.saveToSharePreferences(key_PASSWORD, "0", "");
		}
	}

	private boolean isSaveLoginInfo() {
		return true;
	}
}
